import router from './router'
import store from './store'
// import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  // 动态设置页面标题
  document.title = getPageTitle(to.meta.title)
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      if (!store.getters.userId) {
        const menuList = await store.dispatch('user/getUserInfo')
        const asyncRoutes = await store.dispatch('menu/createNewRoutes', menuList)
        // 处理404
        asyncRoutes.push({ path: '*', redirect: '/404', hidden: true })
        // 组装好的动态路由存到vuex中，之后会和静态路由合并传到sidebar组件中在侧边栏渲染
        store.commit('menu/setRoutes', asyncRoutes)
        // 将动态路由添加到路由器实例对象中
        router.addRoutes(asyncRoutes)
        next(to.path)
      } else {
        next() // 直接放行会经过router.afterEach
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
